
package com.hg.demo.redis.cluster.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hg.demo.redis.cluster.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class RedisServiceImpl implements RedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean set(String key, Object val, long timeout) {
        return set(key, val, timeout, TimeUnit.MILLISECONDS);
    }

    @Override
    public boolean set(String key, Object val, long timeout, TimeUnit timeUnit) {
        if (StrUtil.isEmpty(key)) {
            log.warn("set(),redis设值,warnMsg:key，必填");
            return false;
        } else if (null == val) {
            log.warn("set(),redis设值,warnMsg:val，必填");
            return false;
        } else if (timeout < 1) {
            log.warn("set(),redis设值,warnMsg:timeout，需大于0");
            return false;
        } else if (null == timeUnit) {
            log.warn("set(),redis设值,warnMsg:timeUnit，必填");
            return false;
        }
        try {
            redisTemplate.opsForValue().set(key, val, timeout, timeUnit);
            return true;
        } catch (Exception e) {
            log.error("set(),redis设值,key:{},val:{},timeout:{}, timeUnit:{}", key, val, timeout, timeout);
            log.error("set(),redis设值,errMsg:{}", e.getMessage(), e);
            return false;
        }
    }

    @Override
    public <T> T get(String key, Class<T> clazz) {
        try {
            Object val = redisTemplate.opsForValue().get(key);
            return (null == val ? null : JSONUtil.toBean(JSONUtil.toJsonStr(val), clazz));
        } catch (Exception e) {
            log.error("get(),redis获取缓存,key:{}，clazz:{}", key, clazz);
            log.error("get(),redis获取缓存,errMsg:{}", e.getMessage(), e);
            return null;
        }
    }
}
